package com.lam.mall.controller;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.Result;
import com.lam.common.components.dict.annotation.DictAutoTransfer;
import com.lam.common.constant.MallStateConstant;
import com.lam.common.context.TokenUtils;
import com.lam.common.exception.ParameterErrorException;
import com.lam.common.utils.NumberUtil;
import com.lam.common.utils.StringUtils;
import com.lam.common.validate.ValidateUtil;
import com.lam.common.validate.group.Add;
import com.lam.common.validate.group.Update;
import com.lam.common.validate.model.ValidOperType;
import com.lam.framework.annotation.ParamInject;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.mall.common.constant.MallConstant;
import com.lam.mall.entity.IndexImg;
import com.lam.mall.entity.Product;
import com.lam.mall.param.IndexImgParam;
import com.lam.mall.service.IndexImgService;
import com.lam.mall.service.ProductService;

/**
 * 轮播图设置Controller
 * 
 * @author admin
 * @date 2023-04-20
 */
@Log(title = "轮播图设置")
@ParamInject
@RestController
@RequestMapping("/${adminPath}/mall/indexImg")
public class IndexImgController extends BaseController {

    @Autowired
    private IndexImgService indexImgService;
    @Autowired
    private ProductService productService;

    /**
     * 查询轮播图设置列表
     */
    @Log(oper="分页查询")
    @DictAutoTransfer
    @PreAuthorize("@ss.hasPm('mall:indexImg:list')")
    @GetMapping("/list")
    public Result list(IndexImgParam param) {
    
    	param.setShopId(TokenUtils.getLoginUserShopId());
        startPage();
        orderByColumn("sort_no");
        List<IndexImg> list = indexImgService.selectList(param);
        return Result.ok(getTableData(list));
    }

    /**
     * 获取轮播图设置详细信息
     */
    @DictAutoTransfer
    @Log(oper="根据ID查询")
    @PreAuthorize("@ss.hasPm('mall:indexImg:query')")
    @GetMapping("/{id}")
    public Result getInfo(@PathVariable("id") String id) {
    
    	IndexImg indexImg = indexImgService.selectById(id);
    	if (NumberUtil.eq(indexImg.getType(), 1) && StringUtils.isNotBlank(indexImg.getRelationProd())) {
            Product product = productService.selectById(indexImg.getRelationProd(), false);
            indexImg.setPic(product.getPic());
            indexImg.setProdName(product.getProdName());
        }
    	
        return Result.ok(indexImg);
    }

    /**
     * 新增轮播图设置
     */
    @PreAuthorize("@ss.hasPm('mall:indexImg:add')")
    @Log(businessType = BusinessType.INSERT)
    @PostMapping
    public Result add(@Validated(Add.class) @RequestBody IndexImg indexImg) {
    
    	indexImg.setShopId(TokenUtils.getLoginUserShopId());
        ValidateUtil.validUnique(indexImg, ValidOperType.ADD, MallConstant.UNIQUE_INDEX_IMG_TITLE, "标题已存在！");
        checkProdStatus(indexImg);
        int n = indexImgService.insert(indexImg);
        if(n > 0) {
        	indexImgService.removeIndexImgCache();
        }
        return toAjax(n);
    }

    /**
     * 修改轮播图设置
     */
    @PreAuthorize("@ss.hasPm('mall:indexImg:edit')")
    @Log(businessType = BusinessType.UPDATE)
    @PutMapping
    public Result edit(@Validated(Update.class) @RequestBody IndexImg indexImg) {
    
    	indexImg.setShopId(TokenUtils.getLoginUserShopId());
        ValidateUtil.validUnique(indexImg, ValidOperType.UPDATE, MallConstant.UNIQUE_INDEX_IMG_TITLE, "标题已存在！");
        checkProdStatus(indexImg);
        int n = indexImgService.update(indexImg);
        if(n > 0) {
        	indexImgService.removeIndexImgCache();
        }
        return toAjax(n);
    }

    /**
     * 删除轮播图设置
     */
    @PreAuthorize("@ss.hasPm('mall:indexImg:remove')")
    @Log(businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public Result remove(@PathVariable String id) {
    
    	int n = indexImgService.deleteById(id);
        if(n > 0) {
        	indexImgService.removeIndexImgCache();
        }
        return toAjax(n);
    }
    
    private void checkProdStatus(IndexImg indexImg) {
    	if(NumberUtil.eq(indexImg.getType(), IndexImgParam.STATUS_LINK)) {
        	indexImg.setRelationProd("");
        	if (StringUtils.isBlank(indexImg.getLink())) {
                throw new ParameterErrorException("请填写链接");
            }
        	
        }else if(NumberUtil.eq(indexImg.getType(), IndexImgParam.STATUS_PROD)) {
        	indexImg.setLink("");
        	if (StringUtils.isBlank(indexImg.getRelationProd())) {
                throw new ParameterErrorException("请选择商品");
            }
        	Product product = productService.selectById(indexImg.getRelationProd(), false);
            if (Objects.isNull(product)) {
                throw new ParameterErrorException("商品信息不存在");
            }
            if (!NumberUtil.eq(product.getStatus(), MallStateConstant.STATUS_ONLINE)) {
                throw new ParameterErrorException("该商品未上架，请选择别的商品");
            }
            
        }else {
        	indexImg.setLink("");
        	indexImg.setRelationProd("");
        }
    }

}
